/*
 * @Author: Zhang Kai
 * @Date: 2021-10-20 10:39:44
 * @LastEditors: Zhang Kai
 * @LastEditTime: 2022-06-15 17:54:27
 * @FilePath: /metricsx-standard-ui/src/views/indexlib/index.tsx
 */
// 指标库
import {
  defineComponent,
  onMounted,
  reactive,
  watch,
  ref,
  computed
} from 'vue';
// import classnames from 'classnames';
import './index.scss';
// import LibTable from './indexlibTable';
import API from '@/services';
import SearchForm from '@/components/SearchForm/index';
import Table from '@/components/Table/index';
import { EFavoriteStatus, ECustomColumn } from '@/utils/constants';
import * as RouteNames from '@/router/consts';
import { useRouter } from 'vue-router';
import CustomColumn from '@/components/CustomColumn/index';
import BatchOperates from '@/components/batchOperates/index.vue';
import { ElMessage, ElMessageBox } from 'element-plus/lib/index';
import ThemeTree from '@/components/ThemeTree';
import { downLoadFile } from '@/utils/http';
import _ from 'lodash';
import qs from 'qs';
import { useStore } from '@/store';

const IndexLibrary = defineComponent({
  name: 'IndexLibrary',
  props: {},
  setup: (props, { slots, attrs, emit }) => {
    const store = useStore();

    const visible = computed(() => store.state.indexlibrary.drawerVisible);
    /* 表单 */
    const form: any = reactive({
      cnName: '111',
      type: '',
      gradeId: '',
      subjectId: ''
    });

    /* table List */
    const indexLibraryList: any = reactive({
      list: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      order: undefined,
      sortBy: undefined
    });

    // 选择row
    const multipleSelection: any = reactive({ data: [] });

    // 当前选中节点
    const nodeInfo: any = ref({});

    const router = useRouter();

    /* table loading */
    const TableLoading = ref(false);

    /* form实例 */
    const formRef: any = ref();

    /* 自定义列表 */
    const settings = ref([]);

    /* column */
    const newTableColumn = ref([]);

    /* 指标等级list */
    const IndexGrade: any = ref([]);

    const indexlibType = [
      {
        label: '原子指标',
        value: 1
      },
      {
        label: '派生指标',
        value: 2
      },
      {
        label: '衍生指标',
        value: 3
      }
    ];

    /* table Column */
    const tableColumn: any = ref([
      {
        label: '名称',
        default: ({ row }: any) => (
          <a
            class="cnName"
            onClick={() =>
              router.push({
                name: RouteNames.ROUTE_INDEXDETAIL,
                query: { id: row.id }
              })
            }
          >
            {row.cnName}
          </a>
        ),
        keys: 2
      },
      {
        keys: 1,
        sortable: true
      },
      {
        keys: 8,
        sortable: true
      },
      {
        keys: 11,
        sortable: true
      },
      {
        label: '操作',
        keys: 14,
        default: ({ row }: any) => {
          return (
            <>
              <el-button onClick={() => exports(row.id)} type="text">
                导出
              </el-button>
              <el-button
                type="text"
                onClick={(e: any) => {
                  e.preventDefault();
                  toggleFavoriteStatus(row);
                }}
              >
                {row.favoriteStatus ? '取消收藏' : '收藏'}
              </el-button>
            </>
          );
        }
      }
    ]);

    const exports = (ids: any) => {
      try {
        downLoadFile({
          url: '/metrics/library/batch-export',
          method: 'get',
          params: { ids: ids },
          config: {
            paramsSerializer: function (params: any) {
              return qs.stringify(params, { indices: false }); // param=value1&param=value2
            }
          }
        });
      } catch (error) {
        console.log(error);
      }
    };

    //收藏状态
    const toggleFavoriteStatus = async (row: any) => {
      if (row) {
        const { favoriteStatus, id } = row;
        if (favoriteStatus === 1) {
          // 取消
          const { code } = await API.favoriteMetrics.putFavoriteMetricsById({
            id
          });
          if (code === 200) {
            getIndexLibraryList();
            ElMessage.success('取消收藏成功');
          } else {
            ElMessage.error('取消收藏失败');
          }
        } else {
          //添加
          const { code } = await API.favoriteMetrics.getFavoriteMetricsById({
            id
          });
          if (code === 200) {
            getIndexLibraryList();
            ElMessage.success('收藏成功');
          } else {
            ElMessage.error('收藏失败');
          }
        }
      }
    };

    /* 列表 */
    const getIndexLibraryList = async () => {
      try {
        const { pageNum, pageSize, order, sortBy } = indexLibraryList;
        const { code, data }: any = await API.metrics.getMetricsList({
          pageSize,
          pageNum,
          order,
          sortBy,
          reviewStatus: 5,
          ...form
        });
        if (code === 200 && Array.isArray(data?.list)) {
          indexLibraryList.list = data?.list;
          indexLibraryList.total = +data?.total;
        }
      } catch (error) {
        console.log(
          '🚀 ~ file: index.tsx ~ line 118 ~ getIndexLibraryList ~ error',
          error
        );
      } finally {
        TableLoading.value = false;
      }
    };

    /* 更多操作 */
    const handleBatchOperate = async (v: any) => {
      if (multipleSelection.data.length === 0) {
        ElMessage.warning('请勾选操作项，再进行批量操作');
        return false;
      }
      let code, data;
      TableLoading.value = true;
      const ids = multipleSelection.data.map((d: any) => d.id);
      switch (v) {
        case 'collection':
          ({ code, data } =
            await API.favoriteMetrics.postFavoriteMetricsBatchCreate({ ids }));
          if (code === 200) {
            ElMessage.success('批量收藏成功');
          }
          indexLibraryList.pageNum = 1;
          getIndexLibraryList();
          break;
        case 'cancel-collection':
          ({ code, data } =
            await API.favoriteMetrics.deleteFavoriteMetricsBatchCancel({
              ids
            }));
          if (code === 200) {
            ElMessage.success('批量取消收藏成功');
          }
          indexLibraryList.pageNum = 1;
          getIndexLibraryList();
          break;
        case 'export':
          exports(ids);
          break;
      }
      TableLoading.value = false;
    };

    /* 排序 */
    const sortTable = (obj: any) => {
      if (obj.prop) {
        const order = obj.order === 'ascending' ? 1 : 2;
        indexLibraryList.sortBy = obj.prop;
        indexLibraryList.order = order;
      } else {
        indexLibraryList.sortBy = undefined;
        indexLibraryList.order = undefined;
      }
      getIndexLibraryList();
    };

    /* 获取自定义列列表 */
    const getCustomColumnApi = async () => {
      try {
        const { code, data }: any = await API.userPageSetting.getFindOne({
          pageCode: ECustomColumn?.indexlib
        });
        if (code === 200) {
          settings.value = data?.settings;
          const column = data?.settings?.map((v: any, i: number) => {
            const columnIndex = tableColumn.value?.findIndex(
              (val: any) => val?.keys === v?.keys
            );
            return {
              ...tableColumn.value[columnIndex],
              ...v,
              columnKey: Date.now()
            };
          });
          column.unshift({
            type: 'selection',
            width: '55',
            isCheck: true
          });
          newTableColumn.value = _.compact(column);
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 保存自定义列表 */
    const customColumnConfirm = async (vo: any) => {
      try {
        const { code } = await API.userPageSetting.postSave({
          pageCode: ECustomColumn?.indexlib,
          settings: vo?.map(({ disabled, keys, isCheck, label, prop }: any) => {
            return {
              disabled,
              keys,
              isCheck,
              label,
              prop
            };
          })
        });
        if (code === 200) {
          ElMessage.success('保存配置成功');
          getCustomColumnApi();
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 指标等级枚举 */
    const getIndexGradeId = async () => {
      try {
        const { code, data } =
          await API.dictionaryConfig.getDictionaryConfigEnumTypeByEnumType({
            enumType: 'GRADE'
          });
        if (code === 200 && Array.isArray(data)) {
          IndexGrade.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    onMounted(async () => {
      getCustomColumnApi();
      getIndexLibraryList();
      getIndexGradeId();
    });

    watch(visible, (val: any) => {
      if (!val) {
        getIndexLibraryList();
      }
    });

    return () => {
      return (
        <div class="indexlib-wrap">
          <div class="left-cont">
            <ThemeTree
              reviewStatusList={[5]}
              onGetTreeNode={(treeNode: any) => {
                form.subjectId = treeNode.id;
                getIndexLibraryList();
              }}
            ></ThemeTree>
          </div>
          <div class="right-cont">
            <SearchForm
              num={4}
              onReset={() => {
                formRef.value.resetFields();
                form.subjectId = '';
                getIndexLibraryList();
              }}
              model={form}
              formRef={formRef}
              isSearchBtn={false}
            >
              <el-form-item labelWidth="72px" label="指标名称:" prop="cnName">
                <el-input
                  v-model={form.cnName}
                  style={{ width: '100%' }}
                  placeholder="请输入指标名称搜索"
                  clearable
                  size="large"
                  onChange={() => getIndexLibraryList()}
                ></el-input>
              </el-form-item>

              <el-form-item labelWidth="72px" label="指标类型:" prop="type">
                <el-select
                  style={{ width: '100%' }}
                  v-model={form.type}
                  placeholder="请选择指标类型"
                  clearable
                  size="large"
                  onChange={() => getIndexLibraryList()}
                >
                  {indexlibType?.map((v: any) => (
                    <el-option
                      key={v.value}
                      label={v.label}
                      value={v.value}
                    ></el-option>
                  ))}
                </el-select>
              </el-form-item>

              <el-form-item labelWidth="72px" label="指标等级:" prop="gradeId">
                <el-select
                  style={{ width: '100%' }}
                  v-model={form.gradeId}
                  placeholder="请选择指标等级"
                  clearable
                  size="large"
                  onChange={() => getIndexLibraryList()}
                >
                  {IndexGrade.value?.map((v: any) => (
                    <el-option
                      key={v.value}
                      label={v.label}
                      value={v.value}
                    ></el-option>
                  ))}
                </el-select>
              </el-form-item>
            </SearchForm>

            <div class="table-operate">
              <div class="CustomColumn-operate-wrap">
                <CustomColumn
                  onConfirm={(v: any) => customColumnConfirm(v)}
                  tableColumn={settings.value}
                />
                <div class="checkLength">
                  已选择<b>{multipleSelection.data.length}</b>个列
                </div>
              </div>
              <div class="batch-operate-wrap">
                <BatchOperates
                  v-loading={TableLoading.value}
                  opKeys={['collection', 'cancel-collection', 'export']}
                  onBatchOperate={handleBatchOperate}
                  disabled={multipleSelection.data.length === 0}
                />
              </div>
            </div>

            <Table
              showCheckbox={true}
              v-loading={TableLoading.value}
              onSortChange={sortTable}
              data={indexLibraryList.list}
              column={newTableColumn.value.filter((v: any) => v.isCheck)}
              onSelectionChange={(v: any) => (multipleSelection.data = v)}
              onPageCurrentChange={(page: number) => {
                indexLibraryList.pageNum = page;
                getIndexLibraryList();
              }}
              onPageSizeChange={(size: number) => {
                indexLibraryList.pageNum = 1;
                indexLibraryList.pageSize = size;
                getIndexLibraryList();
              }}
              pagination={{
                total: indexLibraryList.total,
                currentPage: indexLibraryList.pageNum,
                pageSize: indexLibraryList.pageSize
              }}
            />
          </div>
        </div>
      );
    };
  }
});

export default IndexLibrary;
